﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _01原子操作
{
    class Program
    {
        static int i = 0; //初始面包为0
        private static readonly Object _syncRoot = new Object();

        static bool[] flag = new bool []{ false, false };
        static int turn = 0;

        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(Fun1));
            Thread t2 = new Thread(new ThreadStart(Fun2));
            t1.Start();
            t2.Start();
        }
        static void Fun1()
        {
            while (true)
            {
                flag[0] = true;
                turn = 1;
                while (flag[1] && turn == 1)//退出while循环的条件就是，要么另一个线程不想要使用关键区，要么此线程拥有访问权限。
                {
                    Thread.Sleep(18);
                    i++;
                    Console.WriteLine("面包个数:{0},购买人:{1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId);
                }
                flag[0] = false;
                //break;
            }
        }

        static void Fun2()
        {
            while (true)
            {
                flag[1] = true;
                turn = 0;
                while (flag[0] && turn == 0)
                {
                    Thread.Sleep(18);
                    i++;
                    Console.WriteLine("面包个数:{0},购买人:{1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId);
                }
                flag[1] = false;
                //break;
            }
        }

        //static void Fun()
        //{
        //    int id = System.Threading.Thread.CurrentThread.ManagedThreadId;

        //    Console.WriteLine("面包个数:{0},购买人:{1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId);
        //    Thread.Sleep(100);
        //    lock(_syncRoot)
        //    {
        //        while (i <= 3)
        //        {
        //            i++;
        //            Console.WriteLine("面包个数:{0},购买人:{1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId);
        //        }
        //    }
        //}



        //static void T1Fun()
        //{
        //    while (i < 18)
        //    {
        //        i++;
        //        Console.WriteLine("A:" + i.ToString());
        //    }
        //    Thread.Sleep(100);
        //    Console.WriteLine("A Wins");
        //}

        //static void T2Fun()
        //{
        //    while (i > -18)
        //    {
        //        i--;
        //        Console.WriteLine("B:" + i.ToString());
        //    }
        //    Thread.Sleep(100);
        //    Console.WriteLine("B Wins");
        //}
    }
}
